package cn.kgc.kgde.bookstore.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.kgc.kgde.bookstore.entity.Category;
import cn.kgc.kgde.bookstore.mapper.CategoryMapper;
import cn.kgc.kgde.bookstore.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author myt
 * @since 2022-05-23
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    @Override
    public Category findByCategoryId(Long id) {
        return categoryMapper.selectById( id );
    }

    //返回树状json格式数据
    @Override
    public List<Category> getTree(Long pId) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq( "cateParentId", pId );
        List<Category> categoryList = categoryMapper.selectList( wrapper );
        for (Category category : categoryList) {
            List<Category> children = getTree(category.getCateId());
            if (CollUtil.isEmpty(children)) {
                continue;
            }
            category.setChildren( children );
        }
        return categoryList;
    }

    /*
     * 添加分类
     * */
    //添加一级分类 时 cateParentId自动为0
    @Override
    public void addCategory(String cateName, Long cateParentId) {
        Category category = new Category();
        category.setCateName( cateName );
        category.setCateParentId( cateParentId );
        this.categoryMapper.insert(category);
    }

    /*删除分类*/
    @Override
    public void removeCategory(Long cateId) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq( "cateId", cateId );
        this.categoryMapper.delete( wrapper );
    }
}
